package com.zero.qth.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zero.common.core.domain.page.PageDomain;
import com.zero.common.core.utils.bean.BeanUtils;
import com.zero.qth.domain.Driver;
import com.zero.qth.domain.NoticeDriver;
import com.zero.qth.service.IDriverService;
import com.zero.qth.service.INoticeDriverService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.core.NativeDetector;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zero.common.annotation.log.Log;
import com.zero.common.core.basecontroller.BaseController;
import com.zero.common.core.domain.result.AjaxResult;
import com.zero.common.core.enums.BusinessType;
import com.zero.qth.domain.DriverReview;
import com.zero.qth.service.IDriverReviewService;
import com.zero.common.core.utils.poi.ExcelUtil;
import com.zero.common.core.domain.page.TableDataInfo;

/**
 * 司机注册列表Controller
 *
 * @author cai-xu-kun
 * @date 2025-08-15
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "司机注册列表")
@RequestMapping("/qth/driverReview")
public class DriverReviewController extends BaseController {

    private final IDriverReviewService driverReviewService;
    private final INoticeDriverService noticeDriverService;
    private final IDriverService driverService;

    /**
     * 查询司机注册列表分页
     */
    @ApiOperation("查询司机注册列表分页")
    @PreAuthorize("@ss.hasPermi('qth:driverReview:list')")
    @GetMapping("/list")
    public TableDataInfo list(DriverReview driverReview) {
        PageDomain pageDomain = this.startPage();
        Page<DriverReview> p = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
        Page<DriverReview> page = driverReviewService.selectDriverReviewListPage(driverReview, p);
        return this.getDataTable(page);
    }

    /**
     * 导出司机注册列表列表
     */
    @ApiOperation("导出司机注册列表列表")
    @PreAuthorize("@ss.hasPermi('qth:driverReview:export')")
    @Log(title = "司机注册列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DriverReview driverReview) {
        List<DriverReview> list = driverReviewService.selectDriverReviewList(driverReview);
        ExcelUtil<DriverReview> util = new ExcelUtil<DriverReview>(DriverReview.class);
        util.exportExcel(response, list, "司机注册列表数据");
    }

    /**
     * 获取司机注册列表详细信息
     */
    @ApiOperation("获取司机注册列表详细信息")
    @PreAuthorize("@ss.hasPermi('qth:driverReview:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {

        return success(driverReviewService.selectDriverReviewById(id));
    }

    /**
     * 新增司机注册列表
     */
    @ApiOperation("新增司机注册列表")
    @PreAuthorize("@ss.hasPermi('qth:driverReview:add')")
    @Log(title = "司机注册列表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DriverReview driverReview) {
        return toAjax(driverReviewService.insertDriverReview(driverReview));
    }

    /**
     * 修改司机注册列表
     */
    @ApiOperation("修改司机注册列表")
    @PreAuthorize("@ss.hasPermi('qth:driverReview:edit')")
    @Log(title = "司机注册列表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DriverReview driverReview) {
        int result = driverReviewService.updateDriverReview(driverReview);
        Long driverId = driverReview.getDriverId();
        if (result == 0 || driverId == null || driverReview.getAuditStatus() == null) {
            return error();
        }

        if(driverReview.getAuditStatus() == 1) {
            // 更新司机信息
//            LambdaUpdateWrapper<Driver> updateWrapper = new LambdaUpdateWrapper<>();
//            updateWrapper.eq(Driver::getId, driverId)
//                    .set(Driver::getAuditStatus, 1);
//            driverService.update(updateWrapper);
            // 查询司机表是否有该司机记录
            Driver driver = driverService.getById(driverId);
            if (driver == null) {
                return AjaxResult.error("未找到对应的司机记录，无法同步信息");
            }
            // 自动复制字段：将DriverReview的字段赋值给Driver
            BeanUtils.copyProperties(driverReview, driver, "id","createTime","updateTime");
            // 另外处理特殊字段
            driver.setAuditStatus(1);
            driver.setIsNoticeRead(false);
            // 1.3 调用driverService更新司机表（MyBatis-Plus的updateById会自动更新非空字段）
            driverService.updateById(driver);

            // 发通知
            NoticeDriver nativeDetectorOK = new NoticeDriver();
            nativeDetectorOK.setDriverId(driverReview.getDriverId());
            nativeDetectorOK.setType(6);
            nativeDetectorOK.setContent("司机认证审核通过，可以去接单啦！");
            nativeDetectorOK.setCreateTime(new Date());
            noticeDriverService.save(nativeDetectorOK);
        } else if (driverReview.getAuditStatus() == 2){
            // 发通知
            NoticeDriver nativeDetectorNG = new NoticeDriver();
            nativeDetectorNG.setDriverId(driverReview.getDriverId());
            nativeDetectorNG.setType(7);
            nativeDetectorNG.setContent("司机认证审核失败，请补充相关资料或有效证件");
            nativeDetectorNG.setCreateTime(new Date());
            noticeDriverService.save(nativeDetectorNG);
        }
        // 未读
        LambdaUpdateWrapper<Driver> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Driver::getId, driverId)
                .set(Driver::getIsNoticeRead, false);
        driverService.update(updateWrapper);

        return success();
    }

    /**
     * 删除司机注册列表
     */
    @ApiOperation("删除司机注册列表")
    @PreAuthorize("@ss.hasPermi('qth:driverReview:remove')")
    @Log(title = "司机注册列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(driverReviewService.deleteDriverReviewByIds(ids));
    }
}
